<template>
  <div class="default-main ba-table-box">
    <!-- 表格顶部菜单 -->
    <TableHeader
      :buttons="[
        'refresh',
        'add',
        'edit',
        'remove',
        'comSearch',
        'unfold',
        'columnDisplay',
      ]"
      :quick-search-placeholder="placeholder"
      @action="baTable.onTableHeaderAction"
    />
    <!-- 表格 -->
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table ref="tableRef" :pagination="false" @action="baTable.onTableAction" />
    <!-- 表单 -->
    <PopupForm />
  </div>
</template>
<script setup lang="ts">
import { ref, provide, onMounted, reactive, watch, markRaw } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { sysMenu } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import PopupForm from "./popupForm.vue";
import { useMenu } from "@/store/backend/SysM/menu";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useRoute, useRouter } from "vue-router";
import { getDictData } from "@/utils/common";
import Tag from "@/components/dictTag/index.vue";
import TagSearch from "@/components/tagSearch/index.vue";
import { useNavTabs } from "@/store/navTabs";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const router = useRouter();
const dictionary = useDictionary();
const route = useRoute();
const navTabs = useNavTabs();
const menuStore = useMenu();

const state: { statusDict: anyObj } = reactive({
  statusDict: {},
});

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + sysMenu)
      ? (navTabs as any).pageSizeMap.get(route.path + sysMenu)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(sysMenu), //this.api = api菜单管理相关
  {
    pk: "menuId",
    expandAll: false,
    dblClickNotEditColumn: [undefined, "status"],
    column: [
      // { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("menuName"),
        label: "菜单名称",
        prop: "menuName",
        align: "left",
      },
      {
        show: filedShowOff("icon"),
        label: "图标",
        prop: "icon",
        align: "center",
        width: "60",
        render: "icon",
        default: "el-icon-Minus",
        operator: false,
      },
      {
        show: filedShowOff("component"),
        label: "组件路径",
        prop: "component",
        align: "center",
        // "show-overflow-tooltip": true,
        operator: false,
      },
      {
        show: filedShowOff("orderNum"),
        label: "排序",
        prop: "orderNum",
        align: "center",
        width: "50",
        operator: false,
      },
      {
        show: filedShowOff("perms"),
        label: "权限标识",
        prop: "perms",
        align: "center",
        operator: false,
      },
      // {
      //   label: "菜单类型",
      //   prop: "type",
      //   align: "center",
      //   render: "tag",
      //   operator: false,
      //   custom: { menu: "danger", menu_dir: "success", button: "info" },
      //   replaceValue: {
      //     menu: "菜单项",
      //     menu_dir: "菜单目录",
      //     button: "页面按钮",
      //   },
      // },
      {
        show: filedShowOff("remarks"),
        label: "备注",
        prop: "remarks",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("status"),
        label: "菜单状态",
        prop: "status",
        align: "center",
        width: "80",
        render: "customRender",
        customRender: markRaw(Tag),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("createTime"),
        label: "创建时间",
        prop: "createTime",
        align: "center",
        width: "160",
        render: "datetime",
        operator: "RANGE",
      },
      {
        show: operatorShowOff([
          route.path + "/edit",
          route.path + "/add",
          route.path + "/remove",
        ]),
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        operator: false,
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "itemAddButton",
            name: "itemAdd", //与add绑定
            title: "新增",
            text: "",
            type: "primary",
            icon: "iconfont icon-xinzeng",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
    extend: {
      // maxHeight: 600,
    },
  },
  // 表单参数
  {
    // 默认表单数据(添加)
    defaultItems: {
      menuType: "C",
      isFrame: "1", //选项卡
      isCache: "0", //缓存
      status: "0", //状态正常
      visible: "0", //显示
      icon: "el-icon-Minus",
    },
    // 表单字段加载状态
    loading: false,
  },
  // 操作前置方法列表，返回false则取消原操作
  {},
  // 操作后置方法列表，先执行表格本身的查看、删除、编辑、双击、等，再执行本处添加的后置操作
  {
    // 获得编辑数据后 如果icon图标不符合标准就选择默认的icon
    requestEdit: () => {
      if (baTable.form.items && !baTable.form.items.icon)
        baTable.form.items.icon = "el-icon-Minus";
    },
  }
);

//编辑菜单
const editButtonClick = (id: number, params: anyObj) => {
  // menuStore.editMenuItem(id, params).then(res => {
  //   console.log(res);
  // }).catch(err => {
  //   console.log(err);
  // })
};
//获取菜单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("sys_menu_status").then((res: any) => {
    // state.statusDict = getDictData(res);
    dictionary.tag = getDictData(res);
    console.log("获取菜单状态的字典", dictionary.tag);
  });
};
getMenuStatus();
onMounted(() => {
  console.log(router.currentRoute.value);
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(sysMenu);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {}
  );
});

// 相当于表格的onMounted，也可以在页面的onMounted时执行
// baTable.mount();
// 获取数据，可以在页面的onMounted时执行，也可以比如先请求一个API，再执行获取数据
// baTable.getIndex("menuData");//前置调用
//baTable.getIndex()!.then(() => {
//查看请求完毕（已获取到表格数据）
//  baTable.initSort() // 初始化默认排序（如果需要）
//  baTable.dragSort() // 初始化拖拽排序（如果需要）
//})

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
provide("menuStore", menuStore);
</script>
<style lang="scss" scoped>
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
